package utils

import (
	"blog/app/models"
	"context"
	"encoding/json"
	"fmt"
	"github.com/olivere/elastic/v7"
)

// Client https://blog.csdn.net/leo_jk/article/details/123915677
var Client *elastic.Client
var host = "http://localhost:9200/"
var Ctx = context.Background()

// InitClient 初始化
func InitClient() {
	//errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
	var err error
	//初始化客户端
	Client, err = elastic.NewClient(
		elastic.SetSniff(false),
		elastic.SetURL(host),
	)
	if err != nil {
		panic(err)
	}
	//连接服务测试
	_, _, err = Client.Ping(host).Do(context.Background())
	if err != nil {
		panic(err)
	}
	//fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)
	//获取服务端版本号
	esversion, err := Client.ElasticsearchVersion(host)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Elasticsearch version %s\n", esversion)
}

// AddEsDataString 通用写入单条数据,7.x以后表库合一,也就去掉了type,使用index作为表使用
func AddEsDataString(typeName string, docId string, dataJson string) {
	put, err := Client.Index().Index(typeName).Id(docId).BodyString(dataJson).Do(Ctx)
	if err != nil {
		fmt.Println("错误", err)
	}
	fmt.Printf("indexed %s --- index %s --- type %s \n", put.Id, put.Index, put.Type)
}

// ShowEsData 显示表数据
func ShowEsData(typeName string, uId string) {
	//通过id查找
	get1, err := Client.Get().Index(typeName).Id(uId).Do(Ctx)
	if err != nil {
		panic(err)
	}
	if get1.Found {
		//fmt.Printf("Got document %s in version %d from index %s, type %s\n", get1.Id, get1.Version, get1.Index, get1.Type)
		var p models.UserBasic
		err := json.Unmarshal(get1.Source, &p) //将结果集中的数据映射到结构体中
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(p)
	}
}
